package cn.lix.sc.rpc.impl.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 容器上下文工具类
 * @date 2021/4/27
 * @author lix
 * @email sclx1220@163.com
 */
public class SpringContextUtil implements ApplicationContextAware {


    private static ApplicationContext CONTEXT;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        CONTEXT = applicationContext;
    }

    public static <T> T getBean(String name) {
        check();
        return (T) CONTEXT.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        check();
        return CONTEXT.getBean(clazz);
    }

    public static <T> T getBean(Class<T> clazz, String name) {
        check();
        return CONTEXT.getBean(name, clazz);
    }

    public static <T> List<T> getBeansForType(Class<T> clazz) {
        check();
        return CONTEXT.getBeansOfType(clazz).entrySet().stream().map(e -> e.getValue()).collect(Collectors.toList());
    }

    /**
     * 获取容器配置参数
     * @param key
     * @return
     */
    public static String getProperty(String key) {
        check();
        return CONTEXT.getEnvironment().getProperty(key);
    }

    private static void check(){
        if (CONTEXT == null) {
            throw new RuntimeException(" not in spring environment or spring context haven't be load");
        }
    }

}
